package com.zkthink.ceres.pay.wechat.v3.http;

import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.zkthink.ceres.pay.wechat.v3.entity.result.ResultFactory;
import com.zkthink.exception.BizException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.zkthink.ceres.pay.wechat.v3.entity.request.BasePayRequest;
import com.zkthink.ceres.pay.wechat.v3.entity.result.BasePayResult;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * http 客户端辅助类
 * </p>
 *
 * @author vivi.huang
 * @since 2020/5/17
 */
@Slf4j
public class HttpClientHelper {

    private static String mchId = "1900009191"; // 商户号
    private static String mchSerialNo = "1DDE55AD98ED71D6EDD4A4A16996DE7B47773A8C"; // 商户证书序列号

    private CloseableHttpClient httpClient;

    private WxPayService wxService;

    private static String reqdata =
        "{\n" + "    \"stock_id\": \"9433645\",\n" + "    \"stock_creator_mchid\": \"1900006511\",\n"
            + "    \"out_request_no\": \"20190522_001中文11\",\n" + "    \"appid\": \"wxab8acb865bb1637e\"\n" + "}";

    // 你的商户私钥
    private static String privateKey = "-----BEGIN PRIVATE KEY-----\n" + "-----END PRIVATE KEY-----";

    // 你的微信支付平台证书
    private static String certificate = "-----BEGIN CERTIFICATE-----\n" + "-----END CERTIFICATE-----";

    private PrivateKey merchantPrivateKey;
    private X509Certificate wechatpayCertificate;

    public HttpClientHelper() {
//        try {
//            merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
//            wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(certificate.getBytes("utf-8")));
//        } catch (Exception e) {
//            log.error("http client error:[{}]", e.toString());
//        }
    }

    public BasePayResult doRequest(BasePayRequest request) {

        try {
            String json = wxService.postV3(request.getUrl(), request.getRequestData());
            return ResultFactory.create(json, request);
        } catch (WxPayException e) {
            log.error("微信支付V3接口请求异常", e);
            throw new RuntimeException(e);
        }
    }

    public BasePayResult doRequestByHttpClient(BasePayRequest request) {
        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates).build();

        HttpPost httpPost = new HttpPost(request.getUrl());

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getReadTimeoutMs())
            .setConnectTimeout(request.getConnectTimeoutMs()).build();
        httpPost.setConfig(requestConfig);

        StringEntity postEntity = new StringEntity(request.getRequestData(), "UTF-8");
        httpPost.setEntity(postEntity);

        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            return ResultFactory.create(EntityUtils.toString(httpEntity, "UTF-8"), request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}